---
--类名: HistoryView.lua
--创建日期: 2018-4-20
--创建人: 宋建邦
--功能描述: 光辉历程视图
--

local MoLayer = require("app.widget.MoLayer")
local NewRareInfoView = require("app.newBag.views.NewRareInfoView")
local NewguildIconRender = require("app.newGuild.views.renders.NewguildIconRender")

local EACH_ROW_NUM = 5 --报纸日历每行的icon个数
local ITEM_OFFX = 3 --报纸日历item水平方向间距
local ITEM_OFFY = 3 --报纸日历item垂直方向间距

local HistoryView = class("HistoryView",function()
    return MoLayer.new(true)
end)

function HistoryView:ctor(achType,labelType)
    self.vsEvent = 1
    self.vsFoot = 2
    self.vsPaper = 3

    self.mUINode = cc.uiloader:load(Res.HistoryScene)
    self:addChild(self.mUINode)
    self.mUINode:setContentSize(cc.size(display.width,display.height))
    ccui.Helper:doLayout(self.mUINode)

    self.currentPage = 1
    self.currentFootprintPage = 1
    self.currentPaperPage = 1
    self.viewState = self.vsEvent

    HistoryManager:requestEvents(1)
    HistoryManager:requestEvents(2)
    HistoryManager:requestEvents(3)
    HistoryManager:requestEvents(4)
    HistoryManager:requestEvents(5)

    self:initPage()
    self:setPage(1)
    self:initTouch()
    self:initTabs()

    self:addCloseListener()
    self:addDataListener()
    -- HistoryManager:initEvents()
end

function HistoryView:addCloseListener()
    local btnClose = self.mUINode:findChild("Panel/Button_close")
    btnClose:addClickEventListener(function(sender)
        UIHandler:handleMessage({id = Constant.FUNC_TYPE_SPLENDOR_HISTORY,mode = "close"})
    end)
end

function HistoryView:gotoLastPage()
    local pi = math.floor((HistoryManager:getPageCount() + 1)/2) * 2 - 1
    if HistoryManager:getPageCount() ~= self.currentPage then
        self.currentPage = pi
        self:setPage(pi)
    end
end

function HistoryView:addDataListener()
    app:addCustomEventListener("HISTORY_DATA_CHANGE_EVENT", function(event)
        if #event._usedata.msg.events > 0 then
            self:gotoLastPage()
        end
    end, self)
    app:addCustomEventListener("NEWSPAPER_CALENDAR_CHANGE_EVENT", function(event)
        if event._usedata and event._usedata.pageIndex then
            self.currentPaperPage = event._usedata.pageIndex
        end
        self:setPaper(self.currentPaperPage)
    end, self)
end

function HistoryView:setState(s)
    if self.viewState == s then
        return
    end

    self.viewState = s 
    if s == self.vsEvent then
        self:setPage(self.currentPage)
    elseif s == self.vsFoot then
        self.currentFootprintPage = 1
        self:setFootPrint(1)
    elseif s == self.vsPaper then
        HistoryManager:reqGetNewspaperCalendar()
    end 
end

function HistoryView:initPage()
    self.pages = {}
    self.pages[1] = self.mUINode:findChild("Panel/Panel_left")
    self.pages[2] = self.mUINode:findChild("Panel/Panel_right")

    local function initPagePanel(p)
        p.lblAgeName = p:findChild("tlt")
        p.lblPageIndex = p:findChild("num")
        p.panelContent = p:findChild("Panel")
        p.panelContent:setLayoutType(ccui.LayoutType.VERTICAL)
        p.paper = p:findChild("papers")
    end

    initPagePanel(self.pages[1])
    initPagePanel(self.pages[2])
end

function HistoryView:updatePageButtons()
    local preButton = self.mUINode:findChild("Panel/btn_left")
    local nextButton = self.mUINode:findChild("Panel/btn_right")

    preButton:show()
    nextButton:show()

    if self.viewState == self.vsEvent then
        if self.currentPage == 1 then
            preButton:hide()
        end
        if HistoryManager:getPageCount() <= self.currentPage + 1 then
            nextButton:hide()
        end
    elseif self.viewState == self.vsFoot then
        if self.currentFootprintPage == 1 then
            preButton:hide()
        end

        if HistoryManager:getFootPrintPageCount() <= self.currentFootprintPage + 1 then
            nextButton:hide()
        end
    elseif self.viewState == self.vsPaper then
        if self.currentPaperPage == 1 then
            preButton:hide()
        end
        if HistoryManager:getNewsPaperCount() <= self.currentPaperPage + 1 then
            nextButton:hide()
        end
    end
end

function HistoryView:initTouch()
    local preButton = self.mUINode:findChild("Panel/btn_left")
    local nextButton = self.mUINode:findChild("Panel/btn_right")

    local function xPage(aOff)
        if self.viewState == self.vsEvent then
            self.currentPage = math.max(self.currentPage + aOff, 1)
            if HistoryManager:getPageCount() < self.currentPage then
                self.currentPage = self.currentPage - 2
            end
            self:setPage(self.currentPage)
        elseif self.viewState == self.vsFoot then
            self.currentFootprintPage = math.max(self.currentFootprintPage + aOff, 1)
            if aOff > 0 and self.lastLines and #self.lastLines <= 5 then
                self.currentFootprintPage = self.currentFootprintPage - 2
            end
            self:setFootPrint(self.currentFootprintPage)
        elseif self.viewState == self.vsPaper then
            self.currentPaperPage = math.max(self.currentPaperPage + aOff, 1)
            if HistoryManager:getNewsPaperCount() < self.currentPaperPage then
                self.currentPaperPage = self.currentPaperPage - 2
            end
            HistoryManager:reqGetNewspaperCalendar(self.currentPaperPage)
        end
    end

    preButton:addClickEventListener(function(sender)
        xPage(-2)
    end)

    nextButton:addClickEventListener(function(sender)
        xPage(2)
    end)
end

function HistoryView:initTabs()
    self.eventTab = self.mUINode:findChild("Panel/Panel_tab_r/selected_btn_1")
    self.footTab = self.mUINode:findChild("Panel/Panel_tab_r/selected_btn_2")
    self.paperTab = self.mUINode:findChild("Panel/Panel_tab_r/selected_btn_3")
    if UIHandler:isFunctionOpen(Constant.FUNC_TYPE_NEWSPAPER) and 
        not UD:isFeatureClosedByServer(Constant.FUNC_TYPE_NEWSPAPER) then --开启报纸且服务器没有动态关闭
        self.paperTab:setVisible(true)
    end
    
    local btns = {self.eventTab, self.footTab, self.paperTab}
    local function createGroup(aBtns)
        local g = {btns = aBtns}
        -- g.showname = function(btn, b)
        --     if btn:findChild("name_1") then
        --         btn:findChild("name_2"):setVisible(b)
        --     end
        --     if btn:findChild("name_2") then
        --         btn:findChild("name_2"):setVisible(not b)
        --     end
        -- end

        g.select = function(idx)
            g.reset()
            aBtns[idx]:setTouchEnabled(false)
            aBtns[idx]:setBright(false)
            -- g.showname(aBtns[idx], true)
        end
        g.reset = function()
            for i, b in ipairs(aBtns) do
                b:setTouchEnabled( true )
                b:setBright( true )
                -- g.showname(b, false)
            end
        end
        return g 
    end

    local group = createGroup(btns)
    group.select(1)

    self.eventTab:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            self:setState(self.vsEvent)  
            self:gotoLastPage()  
            group.select(1)              
        end
    end )

    self.footTab:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            self:setState(self.vsFoot) 
            group.select(2)
        end
    end )

    self.paperTab:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            self:setState(self.vsPaper)
            group.select(3)
        end
    end)
end

function HistoryView:setPage(aPageIndex)
    local ps = HistoryManager:getPage(aPageIndex)

    local function setAPage(p, d, pi)
        p.panelContent:removeAllChildren()
        p.lblAgeName:setString("")
        p.lblPageIndex:setString("")
        p.panelContent:show()
        p.paper:hide()
        if not d then
            return 
        end
        local a = HistoryManager:getAgeByID(d.ageID)
        if not a then 
            print("age not exist:", d.ageID)
            -- return
            a = {name="ageid:"..tostring(d.ageID)}
        end
        
        p.lblAgeName:setString(L(a.name))
        p.lblPageIndex:setString(tostring(pi))

        local function initItem(i)
            i.lblEventName = i:findChild("Panel/tlt")
            i.lblDesc = i:findChild("Panel/Text")
            i.imgIcon = i:findChild("Panel/head")
            i.detailBtn = i:findChild("Panel/Button")
        end

        local function setCommonGuild(n, d)
            local g = n:findChild("Panel/guild")
            g:show()
            local iconRender = NewguildIconRender.create(g)
            iconRender:setData( 
                {baseIconId = d.FlagBaseIcon, 
                additionIconId = d.FlagAdditionalIcon, 
                baseIconColor = d.FlagBaseIconColor, 
                additionIconColor = d.FlagAdditionalIconColor} ) 
        end

        local function setSmallGuild(n, d)
            n.imgIcon:hide()
            n:findChild("Panel/guild"):show()
            n = n:findChild("Panel/guiil_icon")
            n:show()
            local u = n:findChild("icon_u")
            local b = n:findChild("icon_b")

            u:loadTexture(GD:getImagePath( Res.guildIconPath, d.FlagBaseIcon ))
            b:loadTexture(GD:getImagePath( Res.guildIconPath, d.FlagAdditionalIcon ))

            u:getVirtualRenderer():setColor(
                app:getInst("NewguildModel"):getBaseIconColorList()[ checknumber(d.FlagBaseIconColor) ]
            )
            b:getVirtualRenderer():setColor(
                app:getInst("NewguildModel"):getBaseIconColorList()[ checknumber(d.FlagAdditionalIconColor) ]
            )
        end

        local function getSmallItem()
            local ret = cc.CSLoader:createNode(Res.HistorySmallEvent)
            ret:setContentSize(ret:findChild("Panel"):getContentSize())
            initItem(ret)
            ret.setGuild = setSmallGuild
            return ret 
        end

        local function getMidItem()
            local ret = cc.CSLoader:createNode(Res.HistoryMidEvent)
            ret:setContentSize(ret:findChild("Panel"):getContentSize())
            initItem(ret)
            ret.imgIcon = ret:findChild("Panel/bg")
            ret.setGuild = setCommonGuild
            return ret
        end 

        local function getBigItem()
            local ret = cc.CSLoader:createNode(Res.HistoryBigEvent)
            ret:setContentSize(ret:findChild("Panel"):getContentSize())
            initItem(ret)
            ret.imgIcon = ret:findChild("Panel/bg")
            ret.setGuild = setCommonGuild
            return ret
        end

        local function setItemData(i, d)
            local eventName = L(d.eventTime)
            if d.finishTime and string.len(d.finishTime) >= 0 then
                local t = HistoryManager:transTime(d.finishTime)
                eventName = string.format(L("hanzi_centuryandyear"), tostring(t.y))
                i.lblDesc:setString(HistoryManager:transDesc(L(d.text), d.params, t.y))
            else
                i.lblDesc:setString(HistoryManager:transDesc(L(d.text), d.params))
            end

            if L(d.eventName) ~= d.eventName then
                eventName = eventName.." "..L(d.eventName)
            end

            if i.lblEventName then
                i.lblEventName:setString(eventName)
            end                   

            i.detailBtn:hide()
            if d.descText and string.len(d.descText) > 0 then
                i.detailBtn:show()
                if checknumber(d.descType) == 1 then
                    i.detailBtn:addClickEventListener(function(sender)
                        local triggerNode = i.detailBtn
                        local ft = nil
                        if d.finishRealTime then
                            local t = HistoryManager:transTime(d.finishRealTime)
                            ft = string.format(L("lua_code_text_45"), t.y, t.m, t.d)
                        end
                        local gt = {y=0}
                        if d.finishTime then
                            gt = HistoryManager:transTime(d.finishTime)
                        end
                        local dataTemp = {
                            name=L(d.eventName),
                            string1 = HistoryManager:transDesc(L(d.text), d.params, gt.y),
                            string3 = ft,
                        }

                        if self.eventTips then
                            self.eventTips:setData( dataTemp )
                        else
                            self.eventTips = NewRareInfoView.create()
                            self.eventTips:setData( dataTemp )
                            self.mUINode:addChild( self.eventTips )
                    
                            -- 点击空白区域关闭
                            display.nodeRemoveForNotHit(self.eventTips, function()
                                if self.eventTips then
                                    self.eventTips:removeFromParent()
                                    self.eventTips = nil
                                end
                            end)
                        end
                    
                        local triggerNodeBoundingBox = triggerNode:getBoundingBox()
                        local worldPosTemp = triggerNode:getParent():convertToWorldSpace( cc.p( triggerNodeBoundingBox.x, triggerNodeBoundingBox.y ) )
                        triggerNodeBoundingBox.x = worldPosTemp.x
                        triggerNodeBoundingBox.y = worldPosTemp.y
                        display.adjustNodePos( triggerNodeBoundingBox, self.eventTips )
                    end)
                end
            end            

            local path 
            if d.type == 1 then
                path = d.icon
            elseif d.type == 2 then
                path = d.samllPicture
            elseif d.type == 3 then
                path = d.bigPicture
            end
            if d:getGuildInfo() and i.setGuild then
                -- if d.type == 2 then
                --     path = nil
                -- end
                i.setGuild(i, d:getGuildInfo()[1])
            end
            if path then
                -- print("art/history/"..path..".png")
                i.imgIcon:loadTexture("art/history/"..path..".png")
            end
        end

        for _, v in ipairs(d) do 
            local item = nil
            if v.type == 1 then
                item = getSmallItem()
            elseif v.type == 2 then
                item = getMidItem()
            elseif v.type == 3 then
                item = getBigItem()
            else 
                item = getSmallItem()
            end

            if item then
                setItemData(item, v)
                p.panelContent:addChild(item)
            end
        end
    end

    setAPage(self.pages[1], ps[1], aPageIndex)
    setAPage(self.pages[2], ps[2], aPageIndex + 1)
    self:updatePageButtons()
end

function HistoryView:setFootPrint(aPageIndex)
    local lastYear = nil
    local function setAPage(p, d, si, pi)
        local function getItem(d, n)
            local yearNode = nil
            local ret = cc.CSLoader:createNode(Res.HistoryFootPrint)
            ret:setContentSize(ret:findChild("Panel"):getContentSize())
            ret.timeNode = ret:findChild("Panel/time")
            -- ret.lines = {}
            ret.icons = {}
            -- for i = 1, 5 do
            --     ret.lines[i] = ret:findChild("Panel/line_"..tostring(i))
            -- end

            local timeObj = HistoryManager:transTime(d[1].finishTime)

            ret.timeNode:hide()
            if d.isfirst then
                ret.timeNode:show()
            end
            ret.timeLbl = ret:findChild("Panel/time/time")
            ret.timeLbl:setString(tostring(timeObj.m))
            if lastYear == nil or lastYear ~= timeObj.y then
                local nd = cc.CSLoader:createNode("ui2/history/track_tlt.csb")
                local cs = nd:findChild("Panel"):getContentSize()
                nd:setContentSize(cc.size(cs.width, 15))
                nd:findChild("Panel/time"):setString(tostring(timeObj.y)..L("lua_code_text_516"))
                yearNode = nd 
                lastYear = timeObj.y
            end
            -- else
            --     -- ret.lines[1]:hide()
            --     -- ret.lines[4]:hide()
            -- end

            -- if not n then
            --     ret.lines[1]:show()
            --     ret.lines[5]:hide()
            -- end

            for i = 1, 3 do 
                ret.icons[i] = ret:findChild("Panel/icon_"..tostring(i))
                if d[i] then
                    local cfg = HistoryManager.hevents[d[i].id]
                    if cfg then
                        ret.icons[i]:loadTexture("art/history/"..tostring(cfg.footPrintIcon)..".png")
                        ret.icons[i]:findChild("name"):setString(L(cfg.eventName))
                        ret.icons[i]:setTouchEnabled(true)
                        ret.icons[i]:addTouchEventListener(function(sender, eventType)
                            if eventType == ccui.TouchEventType.ended then
                                local sd = d[i]
                                local d = cfg
                                if d.descText and string.len(d.descText) > 0 then
                                    if checknumber(d.descType) == 1 then
                                        local triggerNode = ret.icons[i]
                                            local ft = nil
                                            local t = {y=0}
                                            if sd.finishRealTime then
                                                t = HistoryManager:transTime(sd.finishRealTime)
                                                ft = string.format(L("lua_code_text_45"), t.y, t.m, t.d)
                                            end
                                            local gt = {y = 0}
                                            if sd.finishTime then
                                                gt = HistoryManager:transTime(sd.finishTime)
                                            end
                                            local dataTemp = {
                                                name=L(d.eventName),
                                                string1 = HistoryManager:transDesc(L(d.text), d.params, gt.y),
                                                string3 = ft,
                                            }
                    
                                            if self.eventTips then
                                                self.eventTips:setData( dataTemp )
                                            else
                                                self.eventTips = NewRareInfoView.create()
                                                self.eventTips:setData( dataTemp )
                                                self.mUINode:addChild( self.eventTips )
                                        
                                                -- 点击空白区域关闭
                                                display.nodeRemoveForNotHit(self.eventTips, function()
                                                    if self.eventTips then
                                                        self.eventTips:removeFromParent()
                                                        self.eventTips = nil
                                                    end
                                                end)
                                            end
                                        
                                            local triggerNodeBoundingBox = triggerNode:getBoundingBox()
                                            local worldPosTemp = triggerNode:getParent():convertToWorldSpace( cc.p( triggerNodeBoundingBox.x, triggerNodeBoundingBox.y ) )
                                            triggerNodeBoundingBox.x = worldPosTemp.x
                                            triggerNodeBoundingBox.y = worldPosTemp.y
                                            display.adjustNodePos( triggerNodeBoundingBox, self.eventTips )
                                    end
                                end  
                            end
                        end )
                    end
                else
                    ret.icons[i]:hide()
                    -- ret.lines[i]:hide()
                end
            end
            return ret, yearNode
        end
        p.panelContent:removeAllChildren()
        p.panelContent:show()
        p.paper:hide()
        if d[si + 1] then
            p.lblAgeName:setString(L("lua_code_text_111"))
            p.lblPageIndex:setString(tostring(pi))
        else
            p.lblAgeName:setString("")
            p.lblPageIndex:setString("")
        end

        for i = 1, 5 do
            if d[si + i] then
                if d[si + i].firstline then
                    local item = cc.CSLoader:createNode("ui2/history/track_top.csb")
                    item:setContentSize(item:findChild("Panel"):getContentSize())

                    item:findChild("Panel/time"):hide()
                    
                    local y, m = HistoryManager:getGameTime()
                    local fstr = string.format(L("history_footprint_mine"), UD.player.name)
                    -- if y > 0 then
                    --     fstr = fstr .. tostring(y) .. L("hanzi_year")
                    -- end
                    -- if m > 0 then
                    --     if y > 0 then
                    --         fstr = fstr .. L("hanzi_zero")
                    --     end
                    --     fstr = fstr .. tostring(m) .. L("hanzi_month")
                    -- end

                    item:findChild("Panel/tlt"):setString(fstr)

                    p.panelContent:addChild(item)
                else
                    local n = d[si + i + 1]
                    if i == 5 then
                        n = nil
                    end
                    local item, year = getItem(d[si + i], n)
                    if year then
                        p.panelContent:addChild(year)
                    end
                    p.panelContent:addChild(item)
                end
            end
        end
    end

    local pd = HistoryManager:getFootPrintPage(aPageIndex)
    self.lastLines = pd
    setAPage(self.pages[1], pd, 0, aPageIndex)
    setAPage(self.pages[2], pd, 5, aPageIndex + 1)
    self:updatePageButtons()
end

function HistoryView:setPaper(aPageIndex)
    local paperInfo = HistoryManager:getNewsPaperCalendarPage(aPageIndex)

    local function setAPage(p, d, pi)
        p.paper:removeAllChildren()
        p.lblAgeName:setString("")
        p.lblPageIndex:setString("")
        p.paper:show()
        p.panelContent:hide()
        if not d then
            return 
        end
        local tltStr = string.format(L("NewsPaperDate"), d.year, d.month)
        p.lblAgeName:setString(tltStr)
        p.lblPageIndex:setString(pi)

        local function getItem()
            local ret = cc.CSLoader:createNode(Res.HistoryPaperNode)
            ret:setContentSize(ret:findChild("Panel"):getContentSize())
            ret.bg = ret:findChild("Panel/bg")
            ret.normalPaper = ret:findChild("Panel/ph_n")
            ret.frontPaper = ret:findChild("Panel/ph_1")
            ret.secondPaper = ret:findChild("Panel/ph_2")
            ret.num = ret:findChild("Panel/num")
            ret.normalPaper:setVisible(false)
            ret.frontPaper:setVisible(false)
            ret.secondPaper:setVisible(false)
            ret.num:setVisible(false)
            return ret 
        end
        local function setItemData(item, day, info)
            if info then
                item.num:setString(day)
                item.num:setVisible(true)
                if info == "Normal" then
                    item.normalPaper:setVisible(true)
                elseif info == "FrontPage" then
                    item.frontPaper:setVisible(true)
                elseif info == "SecondPage" then
                    item.secondPaper:setVisible(true)
                end
                item:findChild("Panel"):setTouchEnabled(true)
                item:findChild("Panel"):addTouchEventListener(function(sender, eventType)
                    if eventType == ccui.TouchEventType.ended then
                        local dateStr = string.format("%s/%s/%s", d.year, d.month, day)
                        HistoryManager:reqGetNewspaperInfo(dateStr)
                    end
                end)
            end
        end

        local panelHeight = 0
        local tempWidth = 0
        local itemWidth, itemHeight
        local paperHeight = p.paper:getContentSize().height
        for i = 1, d.maxday do
            local item = getItem()
            setItemData(item, i, d.info[i])
            p.paper:addChild(item)
            if not itemWidth then
                itemWidth = item:getContentSize().width + ITEM_OFFX
                itemHeight = item:getContentSize().height + ITEM_OFFY
            end
            local curRow = math.floor((i-1) / EACH_ROW_NUM) + 1
            panelHeight = paperHeight - curRow * itemHeight            
            if ((i-1) % EACH_ROW_NUM) == 0 then
                tempWidth = 0                
            end
            item:setPosition(cc.p(tempWidth, panelHeight))
            tempWidth = tempWidth + itemWidth
        end
    end

    setAPage(self.pages[1], paperInfo[1], aPageIndex)
    setAPage(self.pages[2], paperInfo[2], aPageIndex + 1)
    self:updatePageButtons()
end

return HistoryView